<template>
    <div class="rules-code">
        <div class="rules-code-top">
            <span class="titie">校验(Rules)JSON</span>
            <el-button type="text" @click="copy">复制</el-button>
        </div>
        <Vue2AceEditor ref="editor" v-model="editorContent" @init="editorInit" v-bind="editorConfig"></Vue2AceEditor>
    </div>
</template>

<script>
import Vue2AceEditor from 'vue2-ace-editor'
import { clone } from '@/utils/clone'
import { copyText } from '@/utils/dom'
export default {
    components: {
        Vue2AceEditor
    },
    props: {
        schema: Object
    },
    data() {
        return {
            editor: null,
            editorConfig: {
                lang: 'json',
                theme: 'chrome',
                height: 600
            },
            editorContent: ''
        }
    },
    methods: {
        load() {
            const schema = clone(this.schema);
            const rules = {};
            for (const key in schema.properties) {
                if (Array.isArray(schema.properties[key].rules)) {
                    rules[schema.properties[key].model] = schema.properties[key].rules.filter(e => e._checked).map(e => {
                        return {
                            type: e.type,
                            required: e.required,
                            message: e.message,
                            trigger: e.trigger,
                            pattern: e.pattern
                        }
                    })
                }
            }
            this.editorContent = JSON.stringify(rules, null, 2)
        },
        editorInit(editor) {
            this.editor = editor;
            require('brace/ext/language_tools')
            // 设置语言
            require('brace/mode/json')
            require('brace/snippets/json')
            // 设置主题
            require('brace/theme/monokai')
            require('brace/theme/chrome')
            require('brace/theme/crimson_editor')
            // 只读
            this.editor.setReadOnly(true);
            console.log(this.editor);
            // 监听值的变化
            // editor.getSession().on('change', val => {
            //     console.log(editor.getValue());
            // })
        },
        copy() {
            const boo = copyText(this.editor.getValue())
            if (boo) {
                this.$message.success('复制成功')
            } else {
                this.$message.warning('复制失败')
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.rules-code{
    .rules-code-top{
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}
</style>
